package com.example.blogsystem_ssm.controller;

import com.example.blogsystem_ssm.model.Blog;
import com.example.blogsystem_ssm.model.User;
import com.example.blogsystem_ssm.service.WriteBlogService;
import com.example.blogsystem_ssm.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class WriteBlogController {
    @Autowired
    WriteBlogService service;

    @RequestMapping(value = "writeblog")
    public void writeBlog(@RequestParam String title, @RequestParam String content,
                          HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(title == null || content == null || "".equals(title)||"".equals(content)){
            response.setContentType("text/html; charset=utf8");
            response.getWriter().write("发布博客失败！缺少必要的参数！");
            return;
        }
        Blog blog = new Blog();
        // 此处我们蛀牙给 Blog 设置的属性，主题是 title，content，userId（作者信息）
        // postTime【now()方法】 和 blogId（自增主键） 这两个不需要手动指定，都是插入数据库的时候，自动生成的。
        blog.setTitle(title);
        blog.setContent(content);
        // 作者 id 就是当前提交这个博客的用户的身份信息！！！
        User user = (User) request.getSession(false).getAttribute("User");
        blog.setUserId(user.getUserId());
        if(service.insert(blog)){
            response.sendRedirect("/bloghome.html");
        }
    }
}
